package com.birdboot.http;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 响应对象
 * 该类的每一个实例用于表示一个HTTP的响应
 * 每个响应由三个部分构成:状态行,响应头,响应正文
 */
public class HttpServletResponse {
    private static MimetypesFileTypeMap mftm = new MimetypesFileTypeMap();
    private Socket socket;

    //状态行相关信息
    private int statusCode;//状态代码
    private String statusReason;//状态描述
    //响应头相关信息
    private Map<String,String> headers = new HashMap<>();

    //响应正文相关信息
    private File contentFile;//响应正文对应的文件

    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }


    /**
     * 该方法用于将当前响应对象以标准的响应格式发送给客户端(浏览器)
     */
    public void response() throws IOException {
        //3.1发送状态行
        sendStatusLine();
        //3.2发送响应头
        sendHeaders();
        //3.3发送响应正文
        sendContent();
    }
    //发送状态行
    private void sendStatusLine() throws IOException {
        println("HTTP/1.1"+" "+statusCode+" "+statusReason);
    }
    //发送响应头
    private void sendHeaders() throws IOException {
        /*
            headers:
                    key             value
               Content-Type         text/html
               Content-Length       124
               Server               BirdServer
               ...                  ...
         */
        Set<Map.Entry<String,String>> entrySet = headers.entrySet();
        for(Map.Entry<String,String> e : entrySet){
            String key = e.getKey();            //Content-Type
            String value = e.getValue();        //text/html
            println(key + ": " + value);
        }

        //单独发送回车符+换行符表示响应头部分发送完毕
        println("");
    }
    //发送响应正文
    private void sendContent() throws IOException {
        if(contentFile!=null) {//正文文件不为空才发送
            OutputStream out = socket.getOutputStream();
            try (
                    //利用自动关闭特性,确保文件流最后会被关闭释放资源
                    FileInputStream fis = new FileInputStream(contentFile);
            ) {
                int len = 0;
                byte[] buf = new byte[1024 * 10];
                while ((len = fis.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
        }
    }


    /**
     * 向客户端输出一行字符串
     * @param line
     */
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);//发送回车符
        out.write(10);//发送换行符
    }


    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        //设置正文的同时根据该文件添加对应的两个响应头

        String type = mftm.getContentType(contentFile);
        addHeader("Content-Type",type);
        addHeader("Content-Length",contentFile.length()+"");
    }

    /**
     * 向响应对象中添加一组要发送的响应头
     * @param name  响应头名字
     * @param value 响应头值
     */
    public void addHeader(String name,String value){
        headers.put(name,value);
    }

    /**
     * 要求浏览器重定向到指定位置
     * @param uri
     */
    public void sendRedirect(String uri){
        //将状态代码改为302
        setStatusCode(302);
        setStatusReason("Moved Temporarily");
        //添加响应头Location
        addHeader("Location",uri);
    }
}






